package com.zhongshengnetwork.rightbe.lang.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.gsonmodel.CircleLangModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.SmartRankModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.login.LoginActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SmartRankLikeActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener {

    private TopBarView topbar;
    private RefreshLayout mRefreshLayout;
    private ListView listView;
    private MyAdapter adapter = null;
    private int pageindex = 0;
    private static final int Records = 20;
    private List<CircleLangModel> list;

    private SmartRankModel smartRankModel = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        smartRankModel =  (SmartRankModel) getIntent().getSerializableExtra("model");

        setContentView(R.layout.activity_smart_rank_like);

        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);

        if (list == null){
            list = new ArrayList<CircleLangModel>();
        }
        listView = (ListView) findViewById(R.id.rank_listview);
        if (adapter == null){
            adapter = new MyAdapter();
        }
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (list != null && list.size() > i){
                    CircleLangModel model = list.get(i);
                    //进入个人主页
                    Intent intent = new Intent(SmartRankLikeActivity.this, UserLangActivity.class);
                    intent.putExtra(APIKey.useridKey,model.getUserid());
                    intent.putExtra(APIKey.typeKey,1);
                    intent.putExtra(APIKey.titleKey,model.getNickname());
                    startActivity(intent);
                }
            }
        });

        listView.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        listView.setDivider(new ColorDrawable(AppThemeUtils.getInstance().getBackgroundColor()));
        listView.setDividerHeight((int)(AppThemeUtils.DividerHeight* ScreenUtils.getScreenDensity(CustomApplication.mContext)));

        RelativeLayout smart_rank_layout = (RelativeLayout) findViewById(R.id.smart_rank_layout);
        smart_rank_layout.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

        mRefreshLayout = (RefreshLayout)findViewById(R.id.refreshLayout);
        //设置 Header 为 贝塞尔雷达 样式
        mRefreshLayout.setRefreshHeader(new BezierRadarHeader(SmartRankLikeActivity.this).setEnableHorizontalDrag(true));//BezierRadarHeader
        //设置 Footer 为 球脉冲 样式
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(SmartRankLikeActivity.this).setSpinnerStyle(SpinnerStyle.FixedBehind));//BallPulseFooter ClassicsFooter
        mRefreshLayout.setPrimaryColors(AppThemeUtils.getInstance().getRefreshBackgroundColor(),AppThemeUtils.getInstance().getRefreshAccessColor());
        mRefreshLayout.setEnableRefresh(true);//启用刷新
        mRefreshLayout.setEnableLoadMore(false);//启用加载
        //刷新
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //refreshlayout.finishRefresh();
                pageindex = 0;
                getData();
            }
        });
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //refreshLayout.finishLoadMore();
                getData();
            }
        });
        mRefreshLayout.autoRefresh();

    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        finish();
        //Toast.makeText(LangDetailActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();

    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private void getData(){

        new Thread(){
            @Override
            public void run() {
                super.run();
                final Map<String,String> map = new HashMap<String, String>();
                map.put("pageIndex",pageindex+"");
                map.put("pageRecord",Records+"");
                if (CommonUtils.isLogin() == true){
                    map.put("token",CustomApplication.loginModel.getToken());
                }
                if (smartRankModel != null){
                    map.put("dataId", smartRankModel.getRankid());
                }
                String url = "rank/smart/like/list.do";

                HttpsUtils.miniAppDo(map, url,  new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        //listview.stopLoadMore();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (mRefreshLayout.getState() == RefreshState.Refreshing){
                                    mRefreshLayout.finishRefresh();
                                }else if (mRefreshLayout.getState() == RefreshState.Loading){
                                    mRefreshLayout.finishLoadMore();
                                }

                                CommonModel commonModel = GsonTools.getCommonModel(data);
                                if (commonModel.getFlag().equals("1")){
                                    pageindex += 1;
                                    List<CircleLangModel> l = GsonTools.getCircleLangModel(data);
                                    if (l != null && l.size() > 0){
                                        if (l.size() >= Records){
                                            //listview.setPullLoadEnable(true);
                                            mRefreshLayout.setEnableLoadMore(true);
                                        }else {
                                            //listview.setPullLoadEnable(false);
                                            mRefreshLayout.setEnableLoadMore(false);
                                        }
                                        if (pageindex == 1){
                                            list.clear();
                                        }
                                        list.addAll(l);
                                    }else {
                                        //listview.setPullLoadEnable(false);
                                        mRefreshLayout.setEnableLoadMore(false);
                                    }
                                    adapter.notifyDataSetChanged();
                                }else {
                                    if (commonModel.getCode().equals(Constant.UserReturnCode.CODE_10011)){
                                        CustomApplication.showTip(commonModel, SmartRankLikeActivity.this);
                                    }
                                }
                            }
                        });
                    }

                    @Override
                    public void onError(String msg) {
                        //listview.stopLoadMore();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (mRefreshLayout.getState() == RefreshState.Refreshing){
                                    mRefreshLayout.finishRefresh();
                                }else if (mRefreshLayout.getState() == RefreshState.Loading){
                                    mRefreshLayout.finishLoadMore();
                                }

                            }
                        });
                    }
                });
            }
        }.start();
    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }


        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            return super.isEnabled(position);
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            //convertView的复用
            if (convertView == null) {
                convertView = View.inflate(SmartRankLikeActivity.this, R.layout.lang_circle_item,null);
            }
            View view=convertView;
            //view = LayoutInflater.from(getActivity()).inflate(R.layout.lang_circle_item, null);
            ImageView lang_circle_header = (ImageView) view.findViewById(R.id.lang_circle_header);
            ImageView privateIcon = (ImageView) view.findViewById(R.id.private_icon);
            TextView lang_circle_nickname = (TextView) view.findViewById(R.id.lang_circle_nickname);
            Button lang_circle_care = (Button) view.findViewById(R.id.lang_circle_care);
            TextView lang_circle_smart_value = (TextView) view.findViewById(R.id.lang_circle_smart_value);
            TextView lang_circle_count = (TextView) view.findViewById(R.id.lang_circle_count);
            TextView lang_comment_count = (TextView) view.findViewById(R.id.lang_comment_count);
            TextView lang_circle_care_count = (TextView) view.findViewById(R.id.lang_circle_care_count);
            CircleLangModel model = list.get(position);

            Glide.with(SmartRankLikeActivity.this).load(model.getHeader()).transform(new CircleTransform(SmartRankLikeActivity.this)).dontAnimate().into(lang_circle_header);
            if (!CommonUtils.isEmpty(model.getPrivateIcon())){
                privateIcon.setVisibility(View.VISIBLE);
                Glide.with(SmartRankLikeActivity.this).load(model.getPrivateIcon()).transform(new CircleTransform(SmartRankLikeActivity.this)).dontAnimate().into(privateIcon);
            }else {
                privateIcon.setVisibility(View.GONE);
            }
            lang_circle_nickname.setText(model.getNickname());
            lang_circle_care.setTag(position);
            if (model.iscare() == true){
                lang_circle_care.setVisibility(View.INVISIBLE);
            }else {
                lang_circle_care.setVisibility(View.VISIBLE);
                lang_circle_care.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onClickCare((int)v.getTag());
                    }
                });
            }
            lang_circle_smart_value.setText(CommonUtils.getDisplayCount(model.getLevel())+"");
            lang_circle_count.setText((model.getLangcount()-model.getLifecount())+"");
            lang_comment_count.setText(model.getWeishucount()+"");
            lang_circle_care_count.setText(model.getFanscount()+"");

            RelativeLayout lang_circle_item_layout = (RelativeLayout) view.findViewById(R.id.lang_circle_item_layout);
            lang_circle_item_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            LinearLayout lang_circle_line = (LinearLayout) view.findViewById(R.id.lang_circle_line);
            lang_circle_line.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            lang_circle_nickname.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

            ImageView lang_member_icon = (ImageView) view.findViewById(R.id.lang_member_icon);
            if (!CommonUtils.isEmpty(model.getMemberIcon())){
                lang_member_icon.setVisibility(View.VISIBLE);
                try{
                    Glide.with(SmartRankLikeActivity.this).load(model.getMemberIcon()).
                            diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(lang_member_icon);
                }catch (Exception e){
                    LangPublishActivity.uploadError("智慧排行点赞列表加载图片报错："+e.getLocalizedMessage());
                }

            }else {
                lang_member_icon.setVisibility(View.INVISIBLE);
            }

            return view;
        }

    }

    //点击关注
    private void onClickCare(final int position){
        if (list == null || list.size() == 0){
            return;
        }
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(SmartRankLikeActivity.this, LoginActivity.class);
            startActivity(intent);
            return;
        }
        final CircleLangModel model = list.get(position);
        if (model.iscare() == true){
            return;
        }
        model.setIscare(true);
        list.set(position,model);
        adapter.notifyDataSetChanged();

        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put("authorid", model.getUserid());
        String url = "miniapp/"+"langappid"+"/addcare.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
            }

            @Override
            public void onError(String msg) {
            }
        });
    }


}
